package com.ds.rabbitmq.service;

import com.ds.rabbitmq.entity.User;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @program: springboot-1-cache
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-05-24
 **/
@Service
public class UserService {
    @Autowired
    RabbitTemplate rabbitTemplate;
    //监听消息队列注解
    @RabbitListener(queues = {"atguigu","atguigu.emps","gulixueyuan.news"})
    public void receive(User user){
        System.out.println("收到消息"+user);
    }
    @RabbitListener(queues = "atguigu.news")
    public void receive(Message message){
        System.out.println(message.getMessageProperties());
        System.out.println(message.getBody().toString());
        System.out.println("===message===");
    }
    @Async
    public void send(User user){

        rabbitTemplate.convertAndSend("exchange.topic","atguigu.news",user);
        System.out.println("信息发送完成");
        /*
        * 开启了异步编程，这个时候前端就不用等到线程睡眠5秒之后才能收到结果，而是代码到了这一步直接返回给前台，后续的操作会重新开启一个线程来执行
        * 如果返回的结果是需要等到睡眠结果之后才能收到结果的话，使用异步编程会导致前台无法收到结果
        *
        */
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("睡觉结束");
    }
}
